#include "mystdio.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

static MyFILE* Buyfile(int fp,int flag)
{
    MyFILE* f = (MyFILE*)malloc(sizeof(MyFILE));
    if(f == NULL)
        return NULL;
    f->fileno = fp;
    f->flag = flag;
    f->bufflen = 0;
    f->flush_method = LINE_FLUSH;
    memset(f->outbuff,0,sizeof(f->outbuff));
    return f;

}

MyFILE* Myopen(const char* path,const char* mode)
{
    int flag = 0;
    int fp = -1;
    if(strcmp(mode,"w") == 0)
    {
        flag = O_WRONLY | O_CREAT | O_TRUNC;   //写方式打开清空文件内容，没有文件则创建文件，
        fp = open(path,flag,0666);
    }
    else if(strcmp(mode,"r") == 0)
    {
        flag = O_RDONLY;
        fp = open(path,flag);
    }
    else if(strcmp(mode,"a"))
    {
        
        int flag = O_WRONLY | O_CREAT | O_APPEND;
        fp = open(path,flag,0666);
    }
    else
    {
    }
    if(fp < 0) return NULL;
    return Buyfile(fp,flag);

}

int Mywrite(MyFILE* file,void* str,int len)
{
    //使用memcpy函数将str指向的数据拷贝到file结构体中的输出缓冲区outbuffer。
    //拷贝的起始位置是file->outbuffer + file->bufferlen，即缓冲区中当前数据的末尾位置。
    memcpy(file->outbuff+file->bufflen,str,len); 
    file->bufflen += len;
    //判断是否满足刷新条件
    //文件刷新方式是不是行刷新，并且最后一个元素是不是\n
    if((file->flush_method & LINE_FLUSH) && (file->outbuff[file->bufflen -1]) == '\n')
       Myfflush(file);

    return 0;
}

void Myfclose(MyFILE* file)
{
    if(file->fileno < 0)
        return;
    Myfflush(file);
    close(file->fileno);
    free(file);
}

void Myfflush(MyFILE* file)
{
    if(file->bufflen <= 0)
        return;
    //将缓冲区的数据拷贝到内核中
    int n = write(file->fileno,file->outbuff,file->bufflen); //能将内存中已修改的文件数据同步到存储设备
    (void)n;
    fsync(file->fileno);
    file->fileno = 0;
    return;

}

